package myJs.admin

import myJs.Utils.layer
import myJs.Implicits._
import myJs.myPkg.{ColumnOptions, MyFetch, Swal, SwalOptions, TableOptions}
import org.scalajs.dom.{FormData, document}
import scalatags.Text.all._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.Implicits._
import myJs.Tool
import myJs.myPkg.jquery._

import scala.collection.immutable.SeqMap
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._


/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("UserManage")
object UserManage {

  val tableId = "table"

  @JSExport("init")
  def init = {
    initTable
    refreshUser()
    bootStrapValidator

  }

  val operateColumn = js.Array(
    ColumnOptions.field("operate").title("操作").formatter(operateFmt).searchable(false).filterControl("clear")
  )

  def initTable = {
    val map = SeqMap("name" -> "用户名", "createTime" -> "创建时间")
    val columnNames = map.keyList
    val columns = columnNames.map { columnName =>
      val title = map.getOrElse(columnName, columnName)
      val basicOptions = ColumnOptions.field(columnName).title(title).sortable(true)
      columnName match {
        case _ => basicOptions
      }
    }.concat(operateColumn)
    val options = TableOptions.columns(columns.toJSArray).searchOnButton(false).filterControl(false)
    $(s"#${tableId}").bootstrapTable(options)
  }


  @JSExport("refreshUser")
  def refreshUser(f: () => js.Any = () => ()) = {
    val url = g.jsRoutes.controllers.AdminController.getAllUser().url.toString
    MyFetch.get(url = s"${url}",
      headers = Map("Content-Type" -> "application/json")).map { any =>
      val data = any.toJArJDS
      $("#table").bootstrapTable("load", data)
      f()
    }.timeoutDeal
  }

  def operateFmt: js.Function = {
    (v: js.Any, row: js.Dictionary[js.Any]) =>
      val resetStr = a(
        title := "重置",
        onclick := s"UserManage.resetShow('" + row("id") + "')",
        cursor.pointer,
        span(
          em(cls := "fa fa-repeat")
        )
      )
      val deleteStr = a(
        title := "删除",
        cursor.pointer,
        onclick := s"UserManage.deleteData('" + row("id") + "')",
        target := "_blank",
        span(
          em(cls := "fa fa-close")
        )
      )
      Array(resetStr, deleteStr).mkString("&nbsp;")
  }

  @JSExport("resetShow")
  def resetShow(id: String) = {
    val formId = "updateForm"
    val url = g.jsRoutes.controllers.AdminController.getUserById().url.toString
    MyFetch.get(url = s"${url}?id=${id}",
      headers = Map("Content-Type" -> "application/json")).map { any =>
      val rs = any.toJDS
      Tool.fillByNames(rs, formId)
      $("#updateModal").modal("show")
    }.timeoutDeal
  }

  @JSExport("update")
  def update = {
    val formId = "updateForm"
    val bv = $(s"#${formId}").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val data = $(s"#${formId}").serialize()
      val index = layer.alert(Tool.myElement, Tool.layerOptions)
      val url = g.jsRoutes.controllers.AdminController.updateUser().url.toString
      MyFetch.post(url = s"${url}", data = data, headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).
        map { any =>
          refreshUser { () =>
            layer.close(index)
            $("#updateModal").modal("hide")
            bv.resetForm(true)
            Swal.swal(SwalOptions.title("成功").text("密码重置成功!").`type`("success"))
          }
        }.timeoutDeal(index)
    }
  }

  @JSExport("add")
  def add = {
    val bv = $("#form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val data = $(s"#form").serialize()
      val index = layer.alert(Tool.myElement, Tool.layerOptions)
      val url = g.jsRoutes.controllers.AdminController.addUser().url.toString
      val formData = new FormData(document.getElementById("form").toHTMLFormElement)
      MyFetch.post(url = s"${url}", data = data,
        headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map { any =>
        refreshUser { () =>
          layer.close(index)
          $("#addModal").modal("hide")
          bv.resetForm(true)
          Swal.swal(SwalOptions.title("成功").text("新增成功!").`type`("success"))
        }
      }.timeoutDeal(index)
    }
  }

  @JSExport("addShow")
  def addShow = {
    $("#addModal").modal("show")
  }

  def bootStrapValidator = {
    val url = g.jsRoutes.controllers.AdminController.userNameCheck().url.toString
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "name" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "用户名不能为空！"
            ),
            "remote" -> js.Dictionary(
              "message" -> "用户名已存在！",
              "url" -> url,
              "delay" -> 1000,
              "type" -> "POST",
            ),
          )
        ),
        "password" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "密码不能为空！"
            ),
          )
        ),
      )
    )
    g.$("#form").bootstrapValidator(dict)
    updateFormBootStrapValidator
  }

  @JSExport("deleteData")
  def deleteData(id: String) = {
    val options = SwalOptions.title("").text("确定要删除此数据吗？").`type`("warning").showCancelButton(true).
      showConfirmButton(true).confirmButtonClass(Tool.confirmButtonClass).confirmButtonText("确定").closeOnConfirm(false).
      cancelButtonText("取消").showLoaderOnConfirm(true).cancelButtonClass(Tool.cancelButtonClass)
    Swal.swal(options, () => {
      val url = g.jsRoutes.controllers.AdminController.deleteUserById().url.toString
      MyFetch.delete(url = s"${url}?id=${id}", headers = Map("Content-Type" -> "application/json")).map { any =>
        refreshUser { () =>
          Swal.swal(SwalOptions.title("成功").text("删除成功").`type`("success"))
        }
      }.timeoutDeal
    })
  }


  def updateFormBootStrapValidator = {
    val url = g.jsRoutes.controllers.AdminController.userNameCheck().url.toString
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "password" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "密码不能为空！"
            ),
          )
        ),
      )
    )
    g.$("#updateForm").bootstrapValidator(dict)
  }


}
